package com.serkol.annotation;


import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.driving.learning.entity.LoginLog;
import com.serkol.exception.AuthException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;

@Aspect
@Component
public class IsLoginAspect {
    private ThreadLocal<SimpleDateFormat> format = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    //切点表达式，表示加了Auth注解的都是切点，路径是自定义注解的全路径
    @Pointcut("@annotation(IsLogin)")
    public void pointcut() {

    }

    @Around("@annotation(isLogin)")
    public Object operationLogRecord(ProceedingJoinPoint joinPoint, IsLogin isLogin) throws AuthException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(authorization)) {
            LoginLog auth = AuthConstant.getLoginLog();
            //System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL-------------LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL");
          //  System.out.println(auth);
            if (auth == null) {
                throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
            } else {
                if (auth.getUserId() == null) {
                    throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
                }
            }
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
        }
        //响应
        Object responseResult = null;
        try {
            //返回切点处继续执行原方法，并接收原方法的响应
            responseResult = joinPoint.proceed();

        } catch (Throwable e) {
            e.printStackTrace();

            System.out.println("2原方法报错，不需要记录日志");
            throw new AuthException(ResultCode.REQUEST_ERROR_FORBIDDEN);
        }


        return responseResult;
    }

}